﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Input;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace WPBrowser
{
    public partial class MainPage : PhoneApplicationPage
    {
        private List<Uri> lstBrowsedUrl = new List<Uri>();
        private List<string> lstFavoriteUrl = new List<string>();
        private string fileName = "FavoriteUrl.txt";
        private bool isBack = false;

        private bool isFisrtLoad = true;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();

            using (var isoFileStream = new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, myStore))
            {
                using (var isoFileReader = new StreamReader(isoFileStream))
                {
                    while (isoFileReader.EndOfStream == false)
                    {
                        var temp = isoFileReader.ReadLine();
                        lstFavoriteUrl.Add(temp);
                        var menuItem = new ApplicationBarMenuItem(temp);
                        menuItem.Click += menuItem_Click;
                        this.ApplicationBar.MenuItems.Add(menuItem);
                    }
                }
            }
        }
        private void Browse(string url)
        {
            try
            {
                if (url.Contains("http") == false)
                    url = string.Format("http://{0}", url);
                var uri = new Uri(url);
                webBrowser.Source = uri;
            }
            catch (Exception)
            {
            }
        }

        private void Google(string text)
        {
            try
            {
                var url = string.Format("http://google.com.vn/search?q={0}", text);
                var uri = new Uri(url);
                webBrowser.Source = uri;
            }
            catch (Exception)
            {
            }
        }

        private void Save()
        {
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();

            using (var isoFileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myStore))
            {
                //Write the data
                using (var isoFileWriter = new StreamWriter(isoFileStream))
                {
                    foreach (var url in lstFavoriteUrl)
                    {
                        isoFileWriter.WriteLine(url);
                    }
                }
            }
        }

        private void txtUrl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Browse(txtUrl.Text);
                btnBack.Focus();
            }
        }

        private void txtUrl_GotFocus(object sender, RoutedEventArgs e)
        {
            txtUrl.Select(0, txtUrl.Text.Length);
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            Browse(txtUrl.Text);
            btnBack.Focus();
        }

        private void Search_Click(object sender, EventArgs e)
        {
            Google(txtUrl.Text);
            btnBack.Focus();
        }

        private void Add_Click(object sender, EventArgs e)
        {
            if (lstFavoriteUrl.IndexOf(txtUrl.Text) != -1)
                return;

            lstFavoriteUrl.Add(txtUrl.Text);
            var menuItem = new ApplicationBarMenuItem(txtUrl.Text);
            menuItem.Click += menuItem_Click;
            this.ApplicationBar.MenuItems.Add(menuItem);

            Save();
        }

        private void Delete_Click(object sender, EventArgs e)
        {
            int index = -1;
            for (int i = 0; i < this.ApplicationBar.MenuItems.Count; i++)
            {
                var menuItems = this.ApplicationBar.MenuItems[i] as ApplicationBarMenuItem;
                if (menuItems.Text == txtUrl.Text)
                {
                    index = i;
                    break;
                }
            }

            if (index == -1)
                return;

            this.ApplicationBar.MenuItems.RemoveAt(index);
            lstFavoriteUrl.Remove(txtUrl.Text);

            Save();
        }

        private void webBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            this.progressBar.Visibility = System.Windows.Visibility.Visible;
            this.progressBar.IsIndeterminate = true;
        }

        private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (isFisrtLoad == true)//work around for google translate page
            {
                txtUrl.Text = webBrowser.Source.ToString();
                Refresh_Click(null, null);
                isFisrtLoad = false;
                return;
            }

            this.progressBar.Visibility = System.Windows.Visibility.Collapsed;
            this.progressBar.IsIndeterminate = false;

            txtUrl.Text = webBrowser.Source.ToString();

            if (isBack == false)
                lstBrowsedUrl.Add(webBrowser.Source);

            isBack = false;
        }

        void menuItem_Click(object sender, EventArgs e)
        {
            var menuItem = sender as ApplicationBarMenuItem;
            Browse(menuItem.Text);
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            if (lstBrowsedUrl.Count == 1)
                return;

            webBrowser.Source = lstBrowsedUrl[lstBrowsedUrl.Count - 2];
            lstBrowsedUrl.RemoveAt(lstBrowsedUrl.Count - 1);

            btnBack.Focus();

            isBack = true;
        }
    }
}